# -*- encoding: utf-8 -*-
"""
File Name: zabbix_client
Description:
Author : 'lirui'
date: 12/30/2023
Contact: marjey_lee@163.com
Change Activity:
12/30/2023:
"""
import json

import requests

import ll
from modules.zabbix_utils.utils.template.template_loader import TEMPLATE_LOADER


class ZabbixClient:
    def __init__(
            self,
            ip,
            port,
            username,
            password,
            method='http',
            template_loader=TEMPLATE_LOADER,
            new_url=False
    ):
        """"""
        self.ip = ip
        self.port = port
        self.method = method
        self.username = username
        self.password = password
        if new_url:
            self.url = f'{self.method}://{ip}:{port}/api_jsonrpc.php'
        else:
            self.url = f'{self.method}://{ip}:{port}/zabbix/api_jsonrpc.php'
        self.header = {'Content-Type': 'application/json-rpc'}
        self.session = self._load_session()
        self.template_loader = template_loader

    def _load_session(self):
        """
        load sessing
        Returns:

        """
        ll.get_logger().debug(f'Login zabbix client {self.ip}:{self.port}')
        t = TEMPLATE_LOADER.load('user', 'login')
        t['params']['username'] = self.username
        t['params']['password'] = self.password
        return self._post_data(t)['result']

    def get_template(self, obj, func):
        """
        get template.
        """
        return self.template_loader.load(obj, func)

    def _post_data(self, post_json):
        """
        post data to zabbix server.
        Args:
            post_json:

        Returns:

        """
        if hasattr(self, 'session'):
            self.header['Authorization'] = f'Bearer {self.session}'
        ret = requests.post(
            self.url,
            data=json.dumps(post_json),
            headers=self.header
        )
        ret_json = json.loads(ret.text)
        return ret_json

    def check_is_connected(self):
        """
        check is client is connected.
        Returns:

        """
        t = self.template_loader.load('user', 'get')
        res = self._post_data(t)['result']
        if len(res) > 1:
            return True
        return False

    def logout(self):
        ll.get_logger().info(f'Logout zabbix client {self.ip}:{self.port}')
        t = self.template_loader.load('user', 'logout')
        return self._post_data(t)['result']

    def fetch(self, post_info):
        ll.get_logger().debug(f'Request: {post_info}')
        results = self._post_data(post_info)
        ll.get_logger().debug(f'Response: {results}')
        return results['result']

    def insert(self, post_info):
        ll.get_logger().debug(f'Request: {post_info}')
        results = self._post_data(post_info)
        if 'error' in str(results):
            ll.get_logger().warning(f'Response: {results}')
        else:
            ll.get_logger().info(f'Response: {results}')
